package Dicom;

import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class CommonUtils {
    private final static Map<String, Properties> propBundles = new HashMap<String, Properties>();
    private static Properties loadProperties(String file) {
        String fileName = file + ".properties";

        InputStream is = null;
        try {
            is = new FileInputStream(System.getProperty("user.dir")+"/"+fileName);
        } catch (Exception e1) {
        }
        if (is == null) {
            //throw new JoSysException("File (in classpath) not exists: " + fileName);
            URL url=CommonUtils.class.getResource("/"+fileName);
            is = CommonUtils.class.getResourceAsStream("/"+fileName);
        }
        try {
            Properties props = new Properties();
            props.load(is);
            return props;
        } catch (IOException e) {
            //throw new JoSysException("File (in classpath) load failure: " + fileName, e);
        } finally {
            try {
                is.close();
            } catch (IOException ee) {
                //throw new JoSysException(ee);
            }
        }
        return null;
    }

    private static String getProperty(String file, String key) {
        Properties props = propBundles.get(file);
        if (props == null) {
            props = loadProperties(file);
            propBundles.put(file, props);
        }

        return props.getProperty(key);
    }

    public static String getProperty(String key) {
        return getProperty("config", key);
    }

    public static boolean isDicom(String filename) {
        return isDicom(new File(filename));
    }

    public static boolean isDicom(File file) {
        FileInputStream fs;
        try {
            fs = new FileInputStream(file);
            BufferedInputStream is = new BufferedInputStream(fs);
            byte[] data = new byte[132];
            is.read(data, 0, data.length);
            int b0 = data[0] & 255, b1 = data[1] & 255, b2 = data[2] & 255, b3 = data[3] & 255;

            if (data[128] == 68 && data[129] == 73 && data[130] == 67 && data[131] == 77) {
                return true;
            }
            else if ((b0 == 8 || b0 == 2) && b1 == 0 && b3 == 0) {
                return true;
            }
        }
        catch (FileNotFoundException e) {

        }
        catch (IOException e) {

        }
        return false;
    }
}